<template>
  <div class="min-h-screen bg-gray-50">
    <NavBar />

    <div class="max-w-7xl mx-auto px-4 py-8">
      <!-- 非作者引导面板 -->
      <div v-if="!isAuthor && !isAdmin" class="bg-white rounded-2xl shadow p-10 text-center mb-8">
        <div class="text-2xl font-semibold text-gray-800 mb-2">成为作者，开启创作之旅</div>
        <div class="text-gray-500 mb-6">完成实名认证后即可创建、管理你的作品</div>
        <div class="flex items-center justify-center gap-4">
          <button class="btn-primary" @click="$router.push('/author/register')">实名认证并申请作者</button>
          <button class="px-4 py-2 rounded-lg border" @click="$router.replace('/')">返回首页</button>
        </div>
      </div>

      <!-- 顶部横幅（对标番茄作家中心的门户Banner） -->
      <div v-if="isAuthor || isAdmin" class="relative overflow-hidden rounded-2xl mb-8"
           style="background: radial-gradient(120% 120% at 0% 0%, #ffedd5 0%, #ffd1b2 45%, #ffb199 100%);">
        <div class="px-8 py-10 md:px-12 md:py-14">
          <div class="flex items-center gap-3 text-white/90">
            <span class="text-3xl">🍅</span>
            <span class="text-xl font-semibold tracking-wide">作家中心</span>
            <button v-if="isAdmin" @click="$router.push('/admin')" class="ml-auto px-3 py-1.5 rounded-lg bg-white/90 hover:bg-white text-emerald-700 border border-emerald-200">
              管理员操作
            </button>
          </div>
          <div class="mt-4 text-2xl md:text-3xl font-bold text-white">
            你好，{{ authorName }}，开启你的精品IP创作之旅
          </div>
          <div class="mt-3 text-white/90">创建作品、管理章节、查看数据与收益，一站式创作服务</div>
          <div class="mt-6 flex flex-wrap gap-3">
            <button class="btn-primary" @click="createNovel">立即创建作品</button>
            <button class="px-4 py-2 rounded-lg bg-white/90 hover:bg-white text-orange-600" @click="openDrafts">打开草稿箱</button>
            <button class="px-4 py-2 rounded-lg bg-white/90 hover:bg-white text-gray-700" @click="openAnalytics">查看数据概览</button>
            <button class="px-4 py-2 rounded-lg bg-white/90 hover:bg-white text-indigo-700" @click="$router.push('/author/register')">作者认证</button>
          </div>
        </div>
      </div>

      <!-- 主体两栏布局：仅作者/管理员可见（对标门户信息流） -->
      <div v-if="isAuthor || isAdmin" class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        <!-- 左：主内容 -->
        <div class="lg:col-span-8">
          <!-- 数据概览卡片 -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <div v-for="card in statCards" :key="card.key" class="bg-white rounded-lg shadow p-6">
              <div class="text-gray-500">{{ card.title }}</div>
              <div class="mt-2 text-2xl font-semibold">{{ card.value }}</div>
              <div class="mt-1 text-sm text-gray-400">{{ card.subtitle }}</div>
            </div>
          </div>

          <!-- 我的作品列表（番茄“最近更新”风格的表格） -->
          <div class="bg-white rounded-lg shadow">
            <div class="p-6 border-b border-gray-100 flex items-center justify-between">
              <div class="text-lg font-semibold">我的作品</div>
              <div class="flex gap-2">
                <input v-model="searchKeyword" placeholder="搜索标题…" class="px-3 py-2 border border-gray-300 rounded-lg w-56" />
                <select v-model="filterStatus" class="px-3 py-2 border border-gray-300 rounded-lg">
                  <option value="">全部状态</option>
                  <option :value="1">连载中</option>
                  <option :value="2">已完结</option>
                </select>
                <select v-model="filterAudit" class="px-3 py-2 border border-gray-300 rounded-lg">
                  <option value="">审核状态</option>
                  <option :value="1">待审核</option>
                  <option :value="2">已通过</option>
                  <option :value="3">已拒绝</option>
                </select>
                <button class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50" @click="resetFilters">重置</button>
              </div>
            </div>

            <div class="overflow-x-auto">
              <table class="min-w-full">
                <thead>
                  <tr class="bg-gray-50 text-left text-sm text-gray-500">
                    <th class="px-6 py-3">标题</th>
                    <th class="px-6 py-3">分类</th>
                    <th class="px-6 py-3">状态</th>
                    <th class="px-6 py-3">审核</th>
                    <th class="px-6 py-3">字数</th>
                    <th class="px-6 py-3">阅读</th>
                    <th class="px-6 py-3">收藏</th>
                    <th class="px-6 py-3">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in filteredWorks" :key="item.id" class="border-t text-sm">
                    <td class="px-6 py-3 font-medium text-gray-800">{{ item.title }}</td>
                    <td class="px-6 py-3 text-gray-500">{{ item.category_name }}</td>
                    <td class="px-6 py-3">
                      <span :class="badgeClass(item.status)">{{ item.status === 1 ? '连载中' : '已完结' }}</span>
                    </td>
                    <td class="px-6 py-3">
                      <span :class="auditBadgeClass(item.audit_status)">{{ auditText(item.audit_status) }}</span>
                    </td>
                    <td class="px-6 py-3 text-gray-500">{{ item.word_count }}</td>
                    <td class="px-6 py-3 text-gray-500">{{ item.view_count }}</td>
                    <td class="px-6 py-3 text-gray-500">{{ item.collect_count }}</td>
                    <td class="px-6 py-3">
                      <div class="flex gap-2">
                        <button class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50" @click="editWork(item)">编辑</button>
                        <button class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50" @click="manageChapters(item)">章节</button>
                        <button class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50" @click="toggleFeatured(item)">{{ item.is_featured ? '取消推荐' : '推荐' }}</button>
                      </div>
                    </td>
                  </tr>
                  <tr v-if="filteredWorks.length === 0">
                    <td colspan="8" class="px-6 py-10 text-center text-gray-400">暂无作品，点击“立即创建作品”开始创作吧</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- 右：侧边信息区（作家福利/最新资讯/入口） -->
        <div class="lg:col-span-4 space-y-6">
          <div class="bg-white rounded-lg shadow p-6 space-y-4">
            <div class="flex items-center justify-between gap-3">
              <div>
                <div class="text-lg font-semibold">AI 辅助创作</div>
                <p class="text-sm text-gray-500 mt-1">
                  输入创作需求，让 Coze 智能体生成灵感、剧情或角色草案。支持生成多轮消息与图片链接。
                </p>
              </div>
            </div>
            <textarea
              v-model="cozeInput"
              rows="3"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"
              placeholder="例如：帮我生成一段现代都市言情小说的开篇设定，主角是一名女律师……"
            ></textarea>
            <div class="flex items-center justify-between text-xs text-gray-400">
              <span>将作为工作流 input_data 传入智能体</span>
              <button
                class="px-3 py-1.5 rounded-lg bg-orange-500 text-white text-sm hover:bg-orange-600 disabled:opacity-50"
                :disabled="cozeLoading || !cozeInput.trim()"
                @click="runCozeWorkflow"
              >
                {{ cozeLoading ? '运行中...' : '发送给 Coze 智能体' }}
              </button>
            </div>
            <div v-if="cozeError" class="px-3 py-2 text-sm bg-rose-50 text-rose-600 rounded">
              {{ cozeError }}
            </div>
            <div
              v-if="cozeResult"
              class="bg-gray-50 border border-gray-100 rounded p-3 max-h-60 overflow-y-auto text-sm text-gray-700 space-y-3"
            >
              <div v-if="cozeResult.errors && cozeResult.errors.length" class="text-rose-600">
                错误：{{ cozeResult.errors.join('；') }}
              </div>
              <template v-if="cozeResult.messages && cozeResult.messages.length">
                <div
                  v-for="(msg, idx) in cozeResult.messages"
                  :key="idx"
                  class="border border-gray-200 bg-white rounded-lg p-3 shadow-sm space-y-2"
                >
                  <div class="text-xs text-gray-400 uppercase tracking-wide">{{ msg.role || 'assistant' }}</div>
                  <div class="whitespace-pre-wrap leading-6 text-gray-800">
                    {{ msg.content }}
                  </div>
                  <div v-if="msg.meta" class="bg-gray-50 border border-gray-100 rounded px-2 py-1 text-xs text-gray-500">
                    元数据：{{ formatMeta(msg.meta) }}
                  </div>
                  <div
                    v-if="msg.meta?.url && isImageUrl(msg.meta.url)"
                    class="flex items-center justify-center"
                  >
                    <img :src="msg.meta.url" alt="AI 生成图片" class="max-h-48 rounded shadow" />
                  </div>
                </div>
              </template>
              <div v-else class="text-gray-500">暂无返回消息</div>
            </div>
          </div>

          <div class="bg-white rounded-lg shadow p-6">
            <div class="text-lg font-semibold mb-3">作家福利</div>
            <ul class="space-y-2 text-sm text-orange-600">
              <li><a class="hover:underline" href="https://fanqienovel.com/" target="_blank">番茄作家福利区</a></li>
              <li><a class="hover:underline" href="https://fanqienovel.com/" target="_blank">版权专区与改编合作</a></li>
              <li><a class="hover:underline" href="https://fanqienovel.com/" target="_blank">作家助手与帮助中心</a></li>
            </ul>
          </div>

          <div class="bg-white rounded-lg shadow p-6">
            <div class="text-lg font-semibold mb-3">最新资讯</div>
            <ul class="space-y-2 text-sm text-gray-600">
              <li v-for="n in news" :key="n.title" class="flex items-start gap-2">
                <span class="mt-1 w-1.5 h-1.5 rounded-full bg-orange-500"></span>
                <a class="hover:text-orange-600" :href="n.url" target="_blank">{{ n.title }}</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div
    v-if="createModal.visible"
    class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
  >
    <div class="bg-white w-full max-w-3xl rounded-2xl shadow-2xl overflow-hidden">
      <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
        <div>
          <div class="text-lg font-semibold text-gray-800">创建新作品</div>
          <p class="text-xs text-gray-400 mt-1">填写基础信息，生成封面后提交作品，等待编辑审核</p>
        </div>
        <button
          class="w-8 h-8 rounded-full flex items-center justify-center text-gray-400 hover:bg-gray-100"
          @click="closeCreateModal"
        >
          ✕
        </button>
      </div>
      <div class="px-6 py-6 space-y-5 max-h-[80vh] overflow-y-auto">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">作品标题</label>
          <input
            v-model="createModal.form.title"
            type="text"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            placeholder="请输入作品标题"
          />
        </div>

        <div class="grid gap-4 md:grid-cols-2">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">作品分类</label>
            <select
              v-model="createModal.form.category_id"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            >
              <option disabled value="">请选择分类</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                {{ cat.name }}
              </option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">标签</label>
            <input
              v-model="createModal.form.tags"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
              placeholder="例如：玄幻, 热血, 成长"
            />
            <p class="text-xs text-gray-400 mt-1">多个标签请用逗号分隔</p>
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">作品简介</label>
          <textarea
            v-model="createModal.form.description"
            rows="4"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            placeholder="简要介绍作品设定、主角、核心卖点等"
          ></textarea>
        </div>

        <div class="space-y-3">
          <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
            <label class="text-sm font-medium text-gray-700">封面生成与上传</label>
            <span class="text-xs text-gray-400">使用 Coze 智能体生成封面后，再上传到七牛云保存</span>
          </div>
          <div class="flex flex-col md:flex-row gap-3">
            <input
              v-model="createModal.prompt"
              type="text"
              class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
              placeholder="请输入封面提示词，如：热血玄幻风格的年轻剑修站在巅峰"
            />
            <button
              class="px-4 py-2 rounded-lg bg-indigo-500 text-white text-sm hover:bg-indigo-600 disabled:opacity-50"
              :disabled="createModal.generating"
              @click="generateCover"
            >
              {{ createModal.generating ? '生成中...' : '生成封面' }}
            </button>
            <button
              class="px-4 py-2 rounded-lg bg-emerald-500 text-white text-sm hover:bg-emerald-600 disabled:opacity-50"
              :disabled="!createModal.selectedImage || createModal.uploading"
              @click="uploadSelectedImage"
            >
              {{ createModal.uploading ? '上传中...' : '保存到七牛云' }}
            </button>
          </div>
          <div v-if="createModal.generateError" class="text-sm text-rose-600">
            {{ createModal.generateError }}
          </div>

          <div v-if="createModal.generatedImages.length" class="space-y-2">
            <div class="text-xs text-gray-500">点击选择喜欢的封面</div>
            <div class="grid gap-3 grid-cols-2 md:grid-cols-3">
              <button
                v-for="img in createModal.generatedImages"
                :key="img"
                type="button"
                class="relative rounded-lg border transition hover:border-orange-500 overflow-hidden"
                :class="createModal.selectedImage === img ? 'border-orange-500 ring-2 ring-orange-200' : 'border-gray-200'"
                @click="selectGeneratedImage(img)"
              >
                <img :src="img" class="w-full h-40 object-cover" />
                <span
                  v-if="createModal.selectedImage === img"
                  class="absolute top-2 right-2 bg-orange-500 text-white text-xs px-2 py-0.5 rounded"
                >
                  已选择
                </span>
              </button>
            </div>
          </div>

          <div v-if="createModal.uploadMessage" class="text-sm" :class="createModal.uploadMessage.includes('失败') ? 'text-rose-600' : 'text-emerald-600'">
            {{ createModal.uploadMessage }}
          </div>

          <div v-if="createModal.form.cover_url" class="border border-dashed border-gray-300 rounded-lg p-3">
            <div class="text-xs text-gray-500 mb-2">已选封面预览（七牛云）：</div>
            <img :src="createModal.form.cover_url" class="w-full h-48 object-cover rounded" />
          </div>
        </div>
      </div>
      <div class="px-6 py-4 border-t border-gray-100 bg-gray-50 flex items-center justify-end gap-3">
        <button
          class="px-4 py-2 rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-100"
          @click="closeCreateModal"
        >
          取消
        </button>
        <button
          class="px-5 py-2 rounded-lg bg-orange-500 text-white hover:bg-orange-600 disabled:opacity-50"
          :disabled="createModal.submitting"
          @click="submitCreateNovel"
        >
          {{ createModal.submitting ? '提交中...' : '提交作品' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import NavBar from '@/components/layout/NavBar.vue'
import { novelAPI, userAPI } from '@/api/novel'
import { cozeAPI } from '@/api/coze'
import { writerAPI } from '@/api/writer'

const userInfo = ref(null)
const isAdmin = ref(false)
const isAuthor = computed(() => {
  const role = userInfo.value?.role
  return role === 2 || role === 3
})
const authorName = computed(() => userInfo.value?.nickname || '作者')
const authorNameFirstLetter = computed(() => (authorName.value?.[0] || '作'))

// 模拟统计卡片
const statCards = ref([
  { key: 'words', title: '总字数', value: '86,210', subtitle: '含草稿与已发布' },
  { key: 'views', title: '总阅读', value: '128,904', subtitle: '近30天 +3.2%' },
  { key: 'collections', title: '总收藏', value: '4,126', subtitle: '近30天 +1.1%' },
])

const news = ref([
  { title: '创作礼包限时发放，提交作品即可领取创作金', url: 'https://fanqienovel.com/' },
  { title: '2025 年题材风向：现实题材与轻松喜剧热度飙升', url: 'https://fanqienovel.com/' },
  { title: '番茄编辑部：高质量试读技巧分享', url: 'https://fanqienovel.com/' },
])

// 作品列表（从后端获取我的作品）
const works = ref([])
const categories = ref([])
const cozeInput = ref('')
const cozeLoading = ref(false)
const cozeResult = ref(null)
const cozeError = ref(null)

const fetchMyWorks = async () => {
  try {
    const res = await novelAPI.getWriterNovels()
    works.value = res?.data?.list || []
  } catch (e) {
    console.error('获取我的作品失败', e)
    works.value = []
  }
}

const fetchCategories = async () => {
  try {
    const res = await novelAPI.getCategories()
    categories.value = res?.data || []
  } catch (e) {
    console.error('获取分类失败', e)
    categories.value = []
  }
}

// 过滤器
const searchKeyword = ref('')
const filterStatus = ref('')
const filterAudit = ref('')

const filteredWorks = computed(() => {
  return works.value.filter((w) => {
    const byKw = searchKeyword.value ? w.title.includes(searchKeyword.value) : true
    const byStatus = filterStatus.value ? w.status === Number(filterStatus.value) : true
    const byAudit = filterAudit.value ? w.audit_status === Number(filterAudit.value) : true
    return byKw && byStatus && byAudit
  })
})

const resetFilters = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  filterAudit.value = ''
}

const badgeClass = (status) =>
  status === 1
    ? 'px-2 py-0.5 rounded text-xs bg-green-50 text-green-600'
    : 'px-2 py-0.5 rounded text-xs bg-gray-100 text-gray-600'

const auditText = (s) => (s === 1 ? '待审核' : s === 2 ? '已通过' : '已拒绝')
const auditBadgeClass = (s) =>
  s === 2
    ? 'px-2 py-0.5 rounded text-xs bg-emerald-50 text-emerald-600'
    : s === 1
    ? 'px-2 py-0.5 rounded text-xs bg-amber-50 text-amber-600'
    : 'px-2 py-0.5 rounded text-xs bg-rose-50 text-rose-600'

const createModal = reactive({
  visible: false,
  submitting: false,
  prompt: '',
  generating: false,
  generateError: null,
  generatedImages: [],
  selectedImage: '',
  uploading: false,
  uploadedUrl: '',
  uploadMessage: '',
  form: {
    title: '',
    category_id: '',
    description: '',
    tags: '',
    cover_url: '',
  },
})

const openCreateModal = () => {
  if (!categories.value.length) {
    fetchCategories()
  }
  createModal.visible = true
  createModal.submitting = false
  createModal.prompt = ''
  createModal.generating = false
  createModal.generateError = null
  createModal.generatedImages = []
  createModal.selectedImage = ''
  createModal.uploading = false
  createModal.uploadedUrl = ''
  createModal.uploadMessage = ''
  createModal.form = {
    title: '',
    category_id: categories.value?.[0]?.id || '',
    description: '',
    tags: '',
    cover_url: '',
  }
}

const closeCreateModal = () => {
  if (createModal.submitting) return
  createModal.visible = false
}

const extractImageUrls = (messages = []) => {
  const urls = new Set()
  const urlRegex = /https?:\/\/[^\s"]+/g
  messages.forEach((msg) => {
    if (!msg) return
    if (msg.meta?.url) urls.add(msg.meta.url)
    if (msg.meta?.file) urls.add(msg.meta.file)
    if (msg.content) {
      const content = msg.content
      try {
        const parsed = JSON.parse(content)
        if (parsed?.data?.data?.image_urls) {
          parsed.data.data.image_urls.forEach((u) => urls.add(u))
        }
        if (parsed?.arguments?.image_urls) {
          parsed.arguments.image_urls.forEach((u) => urls.add(u))
        }
        if (parsed?.image_urls) {
          parsed.image_urls.forEach((u) => urls.add(u))
        }
      } catch {
        const matches = content.match(urlRegex)
        if (matches) {
          matches.forEach((u) => urls.add(u.replace(/[",;]+$/, '')))
        }
      }
    }
  })
  return Array.from(urls)
}

const generateCover = async () => {
  if (!createModal.prompt.trim()) {
    createModal.generateError = '请输入生成封面的提示词'
    return
  }
  createModal.generating = true
  createModal.generateError = null
  createModal.generatedImages = []
  createModal.selectedImage = ''
  createModal.uploadedUrl = ''
  createModal.form.cover_url = ''
  createModal.uploadMessage = ''
  try {
    const res = await cozeAPI.runWorkflow({
      input_data: { prompt: createModal.prompt.trim() },
      user_id: 'cover_generator',
    })
    const messages = res?.data?.messages || []
    const urls = extractImageUrls(messages)
    if (!urls.length) {
      createModal.generateError = '未解析到图片链接，请尝试更换提示词'
    }
    createModal.generatedImages = urls
  } catch (e) {
    console.error('生成封面失败', e)
    createModal.generateError = e?.response?.data?.detail || e.message || '生成失败'
  } finally {
    createModal.generating = false
  }
}

const selectGeneratedImage = (url) => {
  createModal.selectedImage = url
  createModal.uploadedUrl = ''
  createModal.form.cover_url = ''
  createModal.uploadMessage = ''
}

const uploadSelectedImage = async () => {
  if (!createModal.selectedImage) return
  createModal.uploading = true
  createModal.uploadMessage = ''
  try {
    const res = await writerAPI.uploadCover({ image_url: createModal.selectedImage })
    const uploaded = res?.data?.url
    if (uploaded) {
      createModal.uploadedUrl = uploaded
      createModal.form.cover_url = uploaded
      createModal.uploadMessage = '封面已上传至七牛云'
    } else {
      createModal.uploadMessage = '上传成功，但未获取到地址'
    }
  } catch (e) {
    console.error('上传封面失败', e)
    createModal.uploadMessage = e?.response?.data?.detail || e.message || '上传失败'
  } finally {
    createModal.uploading = false
  }
}

const submitCreateNovel = async () => {
  if (!createModal.form.title.trim()) {
    alert('请输入小说标题')
    return
  }
  if (!createModal.form.category_id) {
    alert('请选择分类')
    return
  }
  const payload = {
    title: createModal.form.title.trim(),
    category_id: Number(createModal.form.category_id),
    description: createModal.form.description?.trim() || undefined,
    cover_url: createModal.form.cover_url || undefined,
    tags: createModal.form.tags
      ? createModal.form.tags.split(',').map((tag) => tag.trim()).filter(Boolean)
      : undefined,
  }
  createModal.submitting = true
  try {
    await writerAPI.createNovel(payload)
    alert('作品创建成功，请等待审核')
    createModal.visible = false
    await fetchMyWorks()
  } catch (e) {
    console.error('创建作品失败', e)
    alert(e?.response?.data?.detail || e.message || '创建失败')
  } finally {
    createModal.submitting = false
  }
}

const createNovel = () => openCreateModal()
const openDrafts = () => alert('后端接口未就绪：将打开草稿箱')
const openAnalytics = () => alert('后端接口未就绪：将打开数据概览')
const editWork = (item) => alert(`编辑《${item.title}》：后端接口未就绪`)
const manageChapters = (item) => alert(`章节管理《${item.title}》：后端接口未就绪`)
const toggleFeatured = (item) => (item.is_featured = !item.is_featured)

const runCozeWorkflow = async () => {
  cozeLoading.value = true
  cozeError.value = null
  cozeResult.value = null
  try {
    const payload = {
      input_data: {
        prompt: cozeInput.value.trim(),
      },
    }
    const res = await cozeAPI.runWorkflow(payload)
    cozeResult.value = res?.data || null
  } catch (e) {
    console.error('触发Coze工作流失败', e)
    cozeError.value = e?.response?.data?.detail || e.message || '调用失败'
  } finally {
    cozeLoading.value = false
  }
}

const isImageUrl = (url) => /^https?:\/\/.+\.(png|jpg|jpeg|gif|webp|svg)(\?.*)?$/i.test(url || '')
const formatMeta = (meta) => {
  try {
    return JSON.stringify(meta)
  } catch {
    return String(meta)
  }
}

onMounted(() => {
  try {
    const raw = localStorage.getItem('user_info')
    userInfo.value = raw ? JSON.parse(raw) : null
  } catch {}
  fetchMyWorks()
  fetchCategories()
  ;(async () => {
    try {
      const res = await userAPI.isAdmin()
      isAdmin.value = !!(res?.data?.is_admin)
    } catch (e) {
      isAdmin.value = false
    }
  })()
})
</script>

<style scoped>
.btn-primary { padding: 0.5rem 1rem; border-radius: 0.5rem; color: #fff; background-color: #f97316; transition: background-color .2s ease; }
.btn-primary:hover { background-color: #ea580c; }
</style>


